<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>API 完整流程测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1000px; margin: 0 auto; }
        .panel { background: white; padding: 20px; margin: 10px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .chat-area { height: 300px; border: 1px solid #ddd; padding: 15px; overflow-y: auto; margin: 10px 0; background: #fafafa; }
        .debug-area { height: 200px; background: #1a1a1a; color: #0f0; padding: 10px; font-family: monospace; font-size: 12px; overflow-y: auto; }
        
        .message-wrapper { display: flex; margin-bottom: 10px; }
        .user-message-wrapper { justify-content: flex-end; }
        .ai-message-wrapper { justify-content: flex-start; }
        .message { display: flex; max-width: 70%; align-items: flex-end; gap: 8px; }
        .user-message { flex-direction: row-reverse; }
        .message-content { padding: 8px 12px; border-radius: 15px; }
        .user-message .message-content { background: #667eea; color: white; }
        .ai-message .message-content { background: #e9ecef; color: #333; }
        .message-avatar { width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; }
        .user-avatar { background: #667eea; color: white; }
        .ai-avatar { background: #6c757d; color: white; }
        
        .loading-state { display: flex; align-items: center; gap: 5px; }
        .loading-spinner { animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        button { padding: 8px 15px; margin: 5px; background: #667eea; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #5a67d8; }
        input { padding: 8px; margin: 5px; border: 1px solid #ddd; border-radius: 4px; width: 300px; }
        
        .status { padding: 5px 10px; margin: 5px; border-radius: 3px; font-size: 12px; }
        .status.success { background: #d4edda; color: #155724; }
        .status.error { background: #f8d7da; color: #721c24; }
        .status.info { background: #d1ecf1; color: #0c5460; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 API 完整流程测试</h1>
        
        <div class="panel">
            <h3>📡 API 状态检查</h3>
            <div id="apiStatus">检查中...</div>
            <button onclick="checkAPIStatus()">重新检查API状态</button>
        </div>
        
        <div class="panel">
            <h3>💬 聊天测试</h3>
            <div>
                <input type="text" id="testMessage" value="找几个Python工程师" placeholder="输入测试消息">
                <button onclick="sendTestMessage()">发送测试</button>
                <button onclick="clearChat()">清空聊天</button>
            </div>
            <div class="chat-area" id="chatArea"></div>
        </div>
        
        <div class="panel">
            <h3>🐛 调试日志</h3>
            <div class="debug-area" id="debugArea"></div>
            <button onclick="clearDebug()">清空日志</button>
        </div>
    </div>

    <script>
        const apiBaseUrl = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/api`;
        let sending = false;
        
        function debugLog(message, type = 'info') {
            const debugArea = document.getElementById('debugArea');
            const time = new Date().toLocaleTimeString();
            const colors = { info: '#0f0', error: '#f44', warn: '#fa0', success: '#0d0' };
            debugArea.innerHTML += `<div style="color: ${colors[type]};">[${time}] ${message}</div>`;
            debugArea.scrollTop = debugArea.scrollHeight;
        }
        
        function setStatus(message, type = 'info') {
            const statusDiv = document.getElementById('apiStatus');
            statusDiv.innerHTML = `<div class="status ${type}">${message}</div>`;
        }
        
        async function checkAPIStatus() {
            debugLog('🔍 检查API状态...', 'info');
            try {
                const response = await fetch(`${apiBaseUrl}/status`);
                const data = await response.json();
                if (data.success && data.initialized) {
                    setStatus('✅ API状态正常，系统已初始化', 'success');
                    debugLog('✅ API状态检查成功', 'success');
                } else {
                    setStatus('⚠️ API响应异常', 'error');
                    debugLog('⚠️ API响应数据异常: ' + JSON.stringify(data), 'warn');
                }
            } catch (error) {
                setStatus('❌ API连接失败: ' + error.message, 'error');
                debugLog('❌ API状态检查失败: ' + error.message, 'error');
            }
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function addMessage(type, content, loading = false) {
            const chatArea = document.getElementById('chatArea');
            const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            const messageEl = document.createElement('div');
            messageEl.className = `message-wrapper ${type}-message-wrapper`;
            messageEl.id = messageId;
            
            debugLog(`🎨 创建消息: type=${type}, loading=${loading}, id=${messageId}`, 'info');
            
            if (type === 'user') {
                messageEl.innerHTML = `
                    <div class="message user-message">
                        <div class="message-content">
                            <div class="message-text">${escapeHtml(content)}</div>
                        </div>
                        <div class="message-avatar user-avatar">👤</div>
                    </div>
                `;
            } else {
                messageEl.innerHTML = `
                    <div class="message ai-message">
                        <div class="message-avatar ai-avatar">🤖</div>
                        <div class="message-content">
                            ${loading ? 
                                `<div class="loading-state">
                                    <div class="loading-spinner">⚙️</div>
                                    <div class="loading-text">伯乐正在思考中...</div>
                                </div>` :
                                `<div class="message-text">${escapeHtml(content)}</div>`
                            }
                        </div>
                    </div>
                `;
            }
            
            chatArea.appendChild(messageEl);
            chatArea.scrollTop = chatArea.scrollHeight;
            
            debugLog(`✅ 消息已添加到DOM，类名: ${messageEl.className}`, 'success');
            return messageId;
        }
        
        function updateMessage(messageId, content) {
            debugLog(`✏️ 尝试更新消息: ${messageId}`, 'info');
            const messageEl = document.getElementById(messageId);
            if (messageEl) {
                debugLog(`📝 找到消息元素: ${messageEl.className}`, 'info');
                const messageContent = messageEl.querySelector('.message-content');
                if (messageContent) {
                    const oldContent = messageContent.innerHTML;
                    debugLog(`🔄 更新前: ${oldContent.includes('loading-state') ? 'loading-state' : 'message-text'}`, 'info');
                    
                    messageContent.innerHTML = `<div class="message-text">${escapeHtml(content)}</div>`;
                    
                    debugLog(`✅ 消息内容已更新为: ${content.substring(0, 30)}...`, 'success');
                    debugLog(`🔄 更新后: message-text`, 'info');
                } else {
                    debugLog(`❌ 未找到 .message-content 元素`, 'error');
                }
            } else {
                debugLog(`❌ 未找到消息元素: ${messageId}`, 'error');
            }
        }
        
        async function sendTestMessage() {
            if (sending) {
                debugLog('⚠️ 正在发送中，请等待...', 'warn');
                return;
            }
            
            const messageInput = document.getElementById('testMessage');
            const message = messageInput.value.trim();
            if (!message) {
                debugLog('❌ 消息不能为空', 'error');
                return;
            }
            
            sending = true;
            debugLog(`🚀 开始发送消息: "${message}"`, 'info');
            debugLog(`📡 API URL: ${apiBaseUrl}/chat`, 'info');
            
            // 步骤1: 添加用户消息
            addMessage('user', message);
            debugLog(`👤 用户消息已添加`, 'info');
            
            // 步骤2: 添加AI loading消息  
            const aiMessageId = addMessage('ai', '', true);
            debugLog(`🤖 AI loading消息已添加: ${aiMessageId}`, 'info');
            
            try {
                // 步骤3: 发送API请求
                debugLog(`📤 发送API请求...`, 'info');
                const response = await fetch(`${apiBaseUrl}/chat`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });
                
                debugLog(`📊 API响应状态: ${response.status} ${response.statusText}`, response.ok ? 'success' : 'error');
                
                if (!response.ok) {
                    const errorText = await response.text();
                    debugLog(`❌ HTTP错误内容: ${errorText}`, 'error');
                    updateMessage(aiMessageId, `请求失败: ${response.status} ${response.statusText}`);
                    return;
                }
                
                const data = await response.json();
                debugLog(`📋 API响应数据: ${JSON.stringify(data, null, 2)}`, 'info');
                debugLog(`🔍 data.success: ${data.success} (${typeof data.success})`, 'info');
                
                // 步骤4: 更新AI消息内容
                if (data.success) {
                    debugLog(`✅ API请求成功，准备更新AI消息`, 'success');
                    const responseMessage = data.message || '处理完成';
                    updateMessage(aiMessageId, responseMessage);
                    
                    if (data.analyzed_candidates && data.analyzed_candidates.length > 0) {
                        debugLog(`📊 响应包含 ${data.analyzed_candidates.length} 个候选人数据`, 'info');
                    }
                } else {
                    debugLog(`❌ API返回错误: ${data.error || '未知错误'}`, 'error');
                    updateMessage(aiMessageId, `处理错误: ${data.error || '未知错误'}`);
                }
                
            } catch (error) {
                debugLog(`❌ 请求异常: ${error.message}`, 'error');
                debugLog(`❌ 异常详情: ${error.stack}`, 'error');
                updateMessage(aiMessageId, '网络连接出现问题，请稍后重试。');
            } finally {
                sending = false;
                debugLog(`🔄 发送状态已重置`, 'info');
            }
        }
        
        function clearChat() {
            document.getElementById('chatArea').innerHTML = '';
            debugLog('🧹 聊天记录已清空', 'info');
        }
        
        function clearDebug() {
            document.getElementById('debugArea').innerHTML = '';
        }
        
        // 页面加载时自动检查API状态
        window.onload = async () => {
            debugLog('🚀 页面加载完成，开始初始化', 'success');
            debugLog(`🔧 API基础URL: ${apiBaseUrl}`, 'info');
            
            await checkAPIStatus();
            
            // 自动执行一次测试
            setTimeout(() => {
                debugLog('🧪 执行自动化测试...', 'info');
                sendTestMessage();
            }, 2000);
        };
    </script>
</body>
</html>










